package com.useful.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.useful.core.constant.SqlConstant;
import com.useful.secure.utils.SecureUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author : wenchao.long
 * @date : Created in 2021/9/22 16:15 周三
 * @description :
 */
@Component
public class FieldFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter(SqlConstant.CREATE_TIME)) {
            this.strictInsertFill(metaObject, SqlConstant.CREATE_TIME, Date::new, Date.class);
        }
        Long userId = SecureUtil.getUserId();
        if (userId != null) {
            if (metaObject.hasGetter(SqlConstant.CREATE_USER)) {
                this.strictInsertFill(metaObject, SqlConstant.CREATE_USER, () -> userId, Long.class);
            }
        }
        if (metaObject.hasGetter(SqlConstant.IS_DELETED)) {
            this.strictInsertFill(metaObject, SqlConstant.IS_DELETED, Integer.class, 0);
        }
        if (metaObject.hasGetter(SqlConstant.STATUS)) {
            this.strictInsertFill(metaObject, SqlConstant.STATUS, Integer.class, 0);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(SqlConstant.UPDATE_TIME)) {
            this.strictUpdateFill(metaObject, SqlConstant.UPDATE_TIME, Date::new, Date.class);
        }
        Long userId = SecureUtil.getUserId();
        if (metaObject.hasGetter(SqlConstant.UPDATE_USER)) {
            this.strictUpdateFill(metaObject, SqlConstant.UPDATE_TIME, () -> userId, Long.class);
        }
    }
}
